package com.nuts.base.config;

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.nuts.base.bean.ResultVO;
import com.nuts.base.core.MyException;
import com.nuts.base.core.ResultEnum;
import com.nuts.base.interceptor.SameUrlDataInterceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * Spring MVC 配置
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

	// @Value("${spring.profiles.active}")
	// private String env;// 当前激活的配置文件

//	@Bean
//	public JavaSerializationConverter javaSerializationConverter() {
//		return new JavaSerializationConverter();
//	}
	
	@Bean(name = "mapperObject")
	public ObjectMapper getObjectMapper() {
	    ObjectMapper om = new ObjectMapper();
	    JavaTimeModule javaTimeModule = new JavaTimeModule();
	    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
	    javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
	    om.registerModule(javaTimeModule);
	    return om;
	}

	// 使用阿里 FastJson 作为JSON MessageConverter
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		FastJsonConfig config = new FastJsonConfig();
		config.setDateFormat("yyyy-MM-dd HH:mm:ss");
		config.setSerializerFeatures(SerializerFeature.PrettyFormat, // 结果是否格式化
				SerializerFeature.WriteMapNullValue, // List字段如果为null,输出为[],而非null
				SerializerFeature.WriteNullListAsEmpty, // 输出值为null的字段
				SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null，输出为""，而不是null
				SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null，输出为0，而不是null
				SerializerFeature.WriteDateUseDateFormat // 日期格式化
		);
		converter.setFastJsonConfig(config);
		converter.setDefaultCharset(Charset.forName("UTF-8"));
		converters.add(converter);
		// converters.add(javaSerializationConverter());
	}

	// 统一异常处理
	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		exceptionResolvers.add(new HandlerExceptionResolver() {
			@Override
			public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
					Object handler, Exception e) {
				// UndeclaredThrowableException异常,查阅资料发现问题应该是spring的aop如果没有正常结束，经过检查点时就会抛出该异常,获取真实异常可以使用
				if (e instanceof UndeclaredThrowableException) {
					e = (Exception) ((UndeclaredThrowableException) e).getUndeclaredThrowable();
				}
				ResultVO result = null;
				if (e instanceof MyException) {// 业务失败的异常，如“账号或密码错误”
					result = new ResultVO(ResultEnum.FAIL.code, e.getMessage());
				} else if (e instanceof NoHandlerFoundException) {
					result = new ResultVO(ResultEnum.NOT_FOUND.code, "接口 [" + request.getRequestURI() + "] 不存在");
				} else if (e instanceof ServletException) {
					result = new ResultVO(ResultEnum.FAIL.code, e.getMessage());
				} else if (e instanceof MethodArgumentNotValidException) {
					// @Validated验证器 异常返回
					MethodArgumentNotValidException ee = ((MethodArgumentNotValidException) e);
					BindingResult error = ee.getBindingResult();
					StringBuilder stringBuilder = new StringBuilder(10);
					List<FieldError> errors = error.getFieldErrors();
					errors.forEach(s -> {
						stringBuilder.append(s.getField() + s.getDefaultMessage() + "!");
					});
					result = new ResultVO(ResultEnum.FAIL.code, stringBuilder.toString());
				} else if (e instanceof BindException) {
					// @Validated验证器 异常返回
					((BindException) e).getBindingResult();
					BindException ee = ((BindException) e);
					List<FieldError> error = ee.getFieldErrors();
					StringBuilder stringBuilder = new StringBuilder(10);
					error.forEach(s -> {
						stringBuilder.append(s.getField() + s.getDefaultMessage() + "!");
					});
					result = new ResultVO(ResultEnum.FAIL.code, stringBuilder.toString());
				} else {
					result = new ResultVO(ResultEnum.INTERNAL_SERVER_ERROR.code,
							"接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
					String message;
					if (handler instanceof HandlerMethod) {
						HandlerMethod handlerMethod = (HandlerMethod) handler;
						message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s", request.getRequestURI(),
								handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(),
								e.getMessage());
					} else {
						message = e.getMessage();
					}
					log.error(message, e);
				}
				log.error(e.getMessage());
				responseResult(response, result);
				return new ModelAndView();
			}

		});
	}

	// 解决跨域问题
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/api/**").allowedOrigins("*").allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600);
	}

	@Bean
	public SameUrlDataInterceptor getSameUrlDataInterceptor() {
		return new SameUrlDataInterceptor();
	}

	// 添加拦截器
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		InterceptorRegistration addInterceptor = registry.addInterceptor(getSameUrlDataInterceptor());
		// 拦截配置
		addInterceptor.addPathPatterns("/api/**");

		// 接口签名认证拦截器，该签名认证比较简单，实际项目中可以使用Json Web Token或其他更好的方式替代。
		// if (!"dev".equals(env)) { // 开发环境忽略签名认证
		// registry.addInterceptor(new HandlerInterceptorAdapter() {
		// @Override
		// public boolean preHandle(HttpServletRequest request,
		// HttpServletResponse response, Object handler)
		// throws Exception {
		// // 验证签名
		// boolean pass = validateSign(request);
		// if (pass) {
		// return true;
		// } else {
		// logger.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",
		// request.getRequestURI(), getIpAddress(request),
		// JSON.toJSONString(request.getParameterMap()));
		//
		// Result result = new Result();
		// result = new ResultVO(ResultEnum.UNAUTHORIZED).setMessage("签名认证失败");
		// responseResult(response, result);
		// return false;
		// }
		// }
		// });
		// }
	}

	private void responseResult(HttpServletResponse response, ResultVO result) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		response.setStatus(200);
		try {
			response.getWriter().write(JSON.toJSONString(result));
		} catch (IOException ex) {
			log.error(ex.getMessage());
		}
	}

	/**
	 * 一个简单的签名认证，规则： 1. 将请求参数按ascii码排序 2. 拼接为a=value&b=value...这样的字符串（不包含sign）
	 * 3. 混合密钥（secret）进行md5获得签名，与请求的签名进行比较
	 */
	// private boolean validateSign(HttpServletRequest request) {
	// String requestSign = request.getParameter("sign");//
	// 获得请求签名，如sign=19e907700db7ad91318424a97c54ed57
	// if (StringUtils.isEmpty(requestSign)) {
	// return false;
	// }
	// List<String> keys = new
	// ArrayList<String>(request.getParameterMap().keySet());
	// keys.remove("sign");// 排除sign参数
	// Collections.sort(keys);// 排序
	//
	// StringBuilder sb = new StringBuilder();
	// for (String key : keys) {
	// sb.append(key).append("=").append(request.getParameter(key)).append("&");//
	// 拼接字符串
	// }
	// String linkString = sb.toString();
	// linkString = StringUtils.substring(linkString, 0, linkString.length() -
	// 1);// 去除最后一个'&'
	//
	// String secret = "Potato";// 密钥，自己修改
	// String sign = DigestUtils.md5Hex(linkString + secret);// 混合密钥md5
	//
	// return StringUtils.equals(sign, requestSign);// 比较
	// }

	// private String getIpAddress(HttpServletRequest request) {
	// String ip = request.getHeader("x-forwarded-for");
	// if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	// ip = request.getHeader("Proxy-Client-IP");
	// }
	// if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	// ip = request.getHeader("WL-Proxy-Client-IP");
	// }
	// if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	// ip = request.getHeader("HTTP_CLIENT_IP");
	// }
	// if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	// ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	// }
	// if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	// ip = request.getRemoteAddr();
	// }
	// // 如果是多级代理，那么取第一个ip为客户端ip
	// if (ip != null && ip.indexOf(",") != -1) {
	// ip = ip.substring(0, ip.indexOf(",")).trim();
	// }
	//
	// return ip;
	// }
}
